(function(){
    const member = new Array();
    const selectedArray = new Array();
    // [
    //     {name:'一等奖',num:1},
    //     {name:'二等奖',num:2},
    //     {name:'三等奖',num:5},
    //     {name:'四等奖',num:10}
    // ];
    var choosed = JSON.parse(localStorage.getItem('choosed')) || {};
    var speed = function(){
        return [0.1 * Math.random() + 0.01, -(0.1 * Math.random() + 0.01)];
    };
    var getKey = function(item){
        return item.username + '-' + item.phone;
    };

    /**
     * 用户
     * @returns {string}
     */
    var createHTML = function(){
        var html = [ '<ul>' ];
        member.forEach(function(item, index){
            item.index = index;
            var key = getKey(item);
            var color = choosed[key] ? 'yellow' : 'white';
            html.push('<li><a href="#" style="color: ' + color + ';">' + item.username + '</a></li>');
        });
        html.push('</ul>');
        return html.join('');
    };
    /**
     * 开始 重置
     * @param count 奖
     * @returns {string[]}
     */
    var lottery = function(count){
        console.log(count)
        var list = canvas.getElementsByTagName('a');
        var color = 'yellow';
        var ret = member
            .filter(function(m, index){
                m.index = index;
                return !choosed[getKey(m)];
            })
            .map(function(m){
                return Object.assign({
                    score: Math.random()
                }, m);
            })
            .sort(function(a, b){
                return a.score - b.score;
            })
            .slice(0, count)
            .map(function(m){
                choosed[getKey(m)] = 1;
                list[m.index].style.color = color;
                return m.username + '<br/>' + m.phone;
            });
        localStorage.setItem('choosed', JSON.stringify(choosed));
        return ret;
    };
    var canvas = document.createElement('canvas');
    canvas.id = 'myCanvas';
    canvas.width = document.body.offsetWidth;
    canvas.height = document.body.offsetHeight;
    document.getElementById('main').appendChild(canvas);
    new Vue({
        el: '#tools',
        data: {
            selected: 30,
            running: false,
            btns: selectedArray
        },
        mounted () {
            // 初始化

            /* 获取用户数据 */
            axios.get('/users')
                .then(function (response) {
                    response.data.forEach(function(item, index){
                        member.push(response.data[index]);
                    });
                    // 加载页面
                    canvas.innerHTML = createHTML();
                    // 加载动画
                    TagCanvas.Start('myCanvas', '', {
                        textColour: null,
                        initial: speed(),
                        dragControl: 1,
                        textHeight: 14
                    });
                })
                .catch(function (error) { // 请求失败处理
                    console.log(error);
                });

            axios.get('/award')
                .then(function (response) {
                    response.data.forEach(function(item, index){
                        selectedArray.push(response.data[index]);
                    });
                    // 加载页面
                    canvas.innerHTML = createHTML();
                    // 加载动画
                    TagCanvas.Start('myCanvas', '', {
                        textColour: null,
                        initial: speed(),
                        dragControl: 1,
                        textHeight: 14
                    });
                })
                .catch(function (error) { // 请求失败处理
                    console.log(error);
                });

        },
        methods: {
            reset: function(){
                if(confirm('确定要重置么？所有之前的抽奖历史将被清除！')){
                    localStorage.clear();
                    location.reload(true);
                }
            },
            onClick: function(num){
                $('#result').css('display', 'none');
                $('#main').removeClass('mask');
                this.selected = num;
            },
            toggle: function(){
                if(this.running){
                    TagCanvas.SetSpeed('myCanvas', speed());
                    var ret = lottery(this.selected);
                    console.log(this.selected)
                    let selectedNum = this.selected;
                    let selectedName;
                    selectedArray.forEach(function(item, index){
                        let num = selectedArray[index].num;
                        if(num === selectedNum){
                            selectedName = selectedArray[index].name;
                        }
                    })
                    if (ret.length === 0) {
                        $('#result').css('display', 'block').html('<span>已抽完</span>');
                        return
                    }
                    $('#result').css('display', 'block').html('<span>' + ret.join('</span><span>') + '</span>');
                    TagCanvas.Reload('myCanvas');
                    setTimeout(function(){
                        // localStorage.setItem(new Date().toString(), JSON.stringify(ret));
                        let storageRanking = {"sort":selectedNum,"ranking":selectedName,"dataList":ret};
                        localStorage.setItem(new Date().toString(), JSON.stringify(storageRanking));
                        $('#main').addClass('mask');
                    }, 300);
                } else {
                    $('#result').css('display', 'none');
                    $('#main').removeClass('mask');
                    TagCanvas.SetSpeed('myCanvas', [5, 1]);
                }
                this.running = !this.running;
            }
        }
    });
})();